package factorytest.iflytek.com.einkiflytekfactorytest.engineerui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;


import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import factorytest.iflytek.com.einkiflytekfactorytest.common.BatteryCurrentThresholdEnum;
import factorytest.iflytek.com.einkiflytekfactorytest.common.PermissionManager;
import factorytest.iflytek.com.einkiflytekfactorytest.R;
import factorytest.iflytek.com.einkiflytekfactorytest.common.BatteryInfo;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.DebugLog;
import factorytest.iflytek.com.einkiflytekfactorytest.common.FTUtils;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.FileReadWrite;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.SystemPropertyUtil;

//电量 0~80%
//
public class BatteryActivity extends Activity {

    private final static String TAG = "BatteryActivity";

    private Context mContext;

    private TextView mTvVoltage;
    private TextView mTvTemperature;
    private TextView mTvLevel;
    private TextView mTvStatus;
    private TextView mTvHealth;
    private TextView mTvCurrent;
    private TextView mTvPlug;

    private BatteryInfo batteryInfo;
    private MyHandler myHandler;

    //获取电流的节点
    private final static String IFYTEK_FACTORY_DIR = FTUtils.getFTStorageDirectory()
            + File.separator + "battery";

    private String recordFilePath = "";



    private static class MyHandler extends Handler {

        private final static int MSG_RECORD_CHARGE_STATUS = 101;
        private final static int MSG_UPDATE_BATTERY_INFO = 102;

        private final static int DELAY_UPDATE_BATTERY_INFO = 5000;
        private final static int DELAY_RECORD_CHARGE_STATUS = 1 * 1000 * 60;

        private final WeakReference<BatteryActivity> activityWeakReference;

        private MyHandler(BatteryActivity activity) {
            super(Looper.getMainLooper());

            activityWeakReference = new WeakReference<BatteryActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            //弱引用会在下一次gc时回收
            BatteryActivity activity = activityWeakReference.get();
            if (activity == null) {
                return;
            }

            switch (msg.what) {
                case MSG_UPDATE_BATTERY_INFO:
                    activity.updateBatteryInfo();
                    sendEmptyMessageDelayed(MSG_UPDATE_BATTERY_INFO, DELAY_UPDATE_BATTERY_INFO);
                    break;
                case MSG_RECORD_CHARGE_STATUS:
                    //存储电池信息
                    activity.recordBattery();
                    //存完之后继续延迟1min发送message来重新储存
                    sendEmptyMessageDelayed(MSG_RECORD_CHARGE_STATUS, DELAY_RECORD_CHARGE_STATUS);
                    break;
                default:
                    break;
            }

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_battery);

        myHandler = new MyHandler(this);


        mTvVoltage = (TextView) findViewById(R.id.tv_voltage);
        mTvTemperature = (TextView) findViewById(R.id.tv_temperature);
        mTvLevel = (TextView) findViewById(R.id.tv_level);
        mTvStatus = (TextView) findViewById(R.id.tv_status);
        mTvHealth = (TextView) findViewById(R.id.tv_health);
        mTvCurrent = (TextView) findViewById(R.id.tv_current);
        mTvPlug = (TextView) findViewById(R.id.tv_plug);

        mContext = this;

        findViewById(R.id.btnFail).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishWithFail();
            }
        });

        initPermission();

        batteryInfo = new BatteryInfo(this);
        batteryInfo.setOnBatteryChangedListener(onBatteryChangedListener);
        batteryInfo.startMonitor();
    }

    private void initPermission() {
        //同时申请多个权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            //同时申请多个权限
            PermissionManager.getInstance(getApplicationContext()).execute(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                    );

        } else {
            //每隔1分钟存储一次电池信息
            myHandler.removeMessages(MyHandler.MSG_RECORD_CHARGE_STATUS);
            myHandler.sendEmptyMessage(MyHandler.MSG_RECORD_CHARGE_STATUS);

        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.getInstance(getApplicationContext()).
                onRequestPermissionsResult(requestCode, permissions, grantResults);

        Log.e(TAG, "battery ~~~~~~~~~~~~~~onRequestPermissionsResult");

        myHandler.removeMessages(MyHandler.MSG_RECORD_CHARGE_STATUS);
        myHandler.sendEmptyMessage(MyHandler.MSG_RECORD_CHARGE_STATUS);


    }

    private void finishWithOK() {
        Toast.makeText(mContext, R.string.test_ok, Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK);
        ActivityCompat.finishAfterTransition(this);
    }

    private void finishWithFail() {
        Toast.makeText(mContext, R.string.test_fail, Toast.LENGTH_SHORT).show();
        setResult(RESULT_CANCELED);
        ActivityCompat.finishAfterTransition(this);
    }

    private void updateBatteryInfo() {

        mTvTemperature.setText(getString(R.string.battery_temperature, batteryInfo.getBatteryTemperature() / 10.0f));
        mTvHealth.setText(getString(R.string.battery_health, batteryInfo.getBatteryHealthString()));
        mTvStatus.setText(getString(R.string.battery_status, batteryInfo.getBatteryStatusString()));
        mTvPlug.setText(getString(R.string.battery_plugged, batteryInfo.getBatteryChargePlugTypeString()));
        mTvVoltage.setText(getString(R.string.battery_voltage, batteryInfo.getBatteryVoltage() / 1000.0f));

        final int current = batteryInfo.getBatteryCurrent_mA();
        final int level = batteryInfo.getBatteryLevel();
        mTvCurrent.setText(getString(R.string.battery_current, current));
        mTvLevel.setText(getString(R.string.battery_level, level));


        BatteryCurrentThresholdEnum thresholdEnum = null;
        for (BatteryCurrentThresholdEnum e : BatteryCurrentThresholdEnum.values()) {
            if (e.isInRange(level)) {
                thresholdEnum = e;
                break;
            }
        }

        if (thresholdEnum != null) {

            DebugLog.e("thresholdEnum current = " + thresholdEnum.getCurrent() + ", now current = " + current);

            if (current >= thresholdEnum.getCurrent()) {
                finishWithOK();
            }
        }
    }

    private void recordBattery() {

        if (TextUtils.isEmpty(recordFilePath)) {
            recordFilePath = getRecordFilePath();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-SS");
        String dateString = sdf.format(new Date());

        StringBuilder sb = new StringBuilder();
        //把电池当前情况存入以sn-时间命名的txt中
        sb.append("time:" + dateString + ";");
        sb.append("voltage:" + batteryInfo.getBatteryVoltage() + ";");
        sb.append("level:" + batteryInfo.getBatteryLevel() + ";");
        sb.append("plug:" + batteryInfo.getBatteryChargePlugTypeString() + ";");
        sb.append("status:" + batteryInfo.getBatteryStatusString() + ";");
        sb.append("current:" + batteryInfo.getBatteryCurrent_mA() + ";");
        sb.append("\n");

        FileReadWrite.writeAppendFile(recordFilePath, sb.toString());

    }


    @Override
    protected void onResume() {
        super.onResume();
        myHandler.sendEmptyMessage(MyHandler.MSG_UPDATE_BATTERY_INFO);
    }

    @Override
    protected void onPause() {
        super.onPause();
        myHandler.removeMessages(MyHandler.MSG_UPDATE_BATTERY_INFO);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        myHandler.removeMessages(MyHandler.MSG_RECORD_CHARGE_STATUS);
        batteryInfo.stopMonitor();
    }


    private BatteryInfo.OnBatteryChangedListener onBatteryChangedListener =
            new BatteryInfo.OnBatteryChangedListener() {
                @Override
                public void onBatteryChangedListener(BatteryInfo info) {

                    updateBatteryInfo();
                }
            };

    public static String getFactoryDir() {
        File file_dir = new File(IFYTEK_FACTORY_DIR);
        if (!(file_dir.exists())) {
            file_dir.mkdirs();
        }

        return file_dir.getAbsolutePath();
    }

    private static String getRecordFilePath() {
        //获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-SS");
        String dateString = sdf.format(new Date());
        //
        String sn = SystemPropertyUtil.getSystemProperty(("sys.serialno"));
        String txt = sn + "-" + dateString + ".txt";
        return getFactoryDir() + File.separator + txt;
    }


}
